package com.paiai.lslease.service.appuser;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.paiai.lslease.auto.dao.AppHouseDAO;
import com.paiai.lslease.auto.dao.AppLandlordAuthDAO;
import com.paiai.lslease.auto.dao.AppSocketDAO;
import com.paiai.lslease.auto.dao.AppSysUserDAO;
import com.paiai.lslease.auto.dao.AppSysUserRoleDAO;
import com.paiai.lslease.auto.model.AppHouse;
import com.paiai.lslease.auto.model.AppHouseExample;
import com.paiai.lslease.auto.model.AppLandlordAuthExample;
import com.paiai.lslease.auto.model.AppSocket;
import com.paiai.lslease.auto.model.AppSocketExample;
import com.paiai.lslease.auto.model.AppSocketExample.Criteria;
import com.paiai.lslease.auto.model.AppSysUser;
import com.paiai.lslease.auto.model.AppSysUserExample;
import com.paiai.lslease.auto.model.AppSysUserRoleExample;
import com.paiai.lslease.base.AppResult;
import com.paiai.lslease.base.SystemConstants;
import com.paiai.lslease.model.bo.MobileModifyBo;
import com.paiai.lslease.model.vo.AppSocketVo;
import com.paiai.lslease.model.vo.MineVo;

/** 
* @author chenmfa
* @version 创建时间：2017年10月20日 上午8:33:31 
* @description
*/
@Service("appUserModuleService")
public class AppUserModuleServiceImpl implements AppUserModuleService {

  @Autowired
  AppSysUserDAO appSysUserDAO;
  @Autowired
  AppSocketDAO appSocketDAO;
  @Autowired
  AppHouseDAO appHouseDAO;
  @Autowired
  AppLandlordAuthDAO appLandlordAuthDAO;
  @Autowired
  AppSysUserRoleDAO appSysUserRoleDAO;
  /**
   * @description 修改用户手机号码
   * @throws SQLException
   */
  public AppResult updateUserMobile(MobileModifyBo record) throws SQLException{
    AppResult result;
    AppSysUser user = queryUserInfo(record.getAccount());
    if(null == user){
      result = AppResult.newFailResult("用户不存在");
    }else{
      AppSysUser existBind = queryUserInfo(record.getMobile());
      if(null == existBind){
        //用户不存在,可以绑定
        AppSysUser newUser = new AppSysUser();
        newUser.setMobile(record.getMobile());
        AppSysUserExample example = new AppSysUserExample();
        example.createCriteria().andMobileEqualTo(record.getAccount())
        .andStateEqualTo(1);
        appSysUserDAO.updateByExampleSelective(newUser, example);
        user.setMobile(record.getMobile());        
        result = AppResult.newSusscessResult("修改密码成功",swapObjectIntoList(user)); 
      }else{
        result = AppResult.newFailResult("该手机号码已绑定"); 
      }
    }
    return result;
  }
  
  /**
   * @description 添加网关插头
   */
  public AppResult addUserGateway(AppSocket socket,String mobile) throws SQLException{
    AppSocketExample example = new AppSocketExample();
    example.createCriteria().andMacEqualTo(socket.getMac());
    //清除已经存在的旧设备
    appSocketDAO.deleteByExample(example);
    //查询用户id
    AppSysUser user = queryUserInfo(mobile);
    if(null == user){
      return AppResult.newFailResult("用户不存在");
    }
    //添加新设备
    Date da = new Date();
    socket.setInsertTime(da);
    socket.setUpdateTime(da);
    socket.setManageUserId(user.getId());
    socket.setItem1("1");
    appSocketDAO.insertSelective(socket);
    return AppResult.newSusscessResult("添加成功");
  }
  
  /**
   * @description 修改网关wifi
   */
  public int updateGateWifi(AppSocket socket) throws SQLException{
    AppSocketExample example = new AppSocketExample();
    example.createCriteria().andMacEqualTo(socket.getMac()).andItem1EqualTo("1");
    return appSocketDAO.updateByExampleSelective(socket, example);
  }
  /**
   * @description 删除网关
   * @param mac
   */
  public int deleteGateWifi(String mac) throws SQLException{
    AppSocketExample example = new AppSocketExample();
    example.createCriteria().andMacEqualTo(mac);
    return appSocketDAO.deleteByExample(example);
  }
  
  /**
   * @description 查询用户网关
   * @param mac
   */
  public AppResult queryUserSocket(String mobile, String mac) throws SQLException{
    AppResult result;
    AppSysUser userInfo = queryUserInfo(mobile);
    if(null == userInfo){
      result = AppResult.newFailResult("用户不存在");
    }else{      
      AppSocketExample example = new AppSocketExample();
      Criteria ct = example.createCriteria();
      ct.andManageUserIdEqualTo(userInfo.getId());
      if(null != mac){
        ct.andMacEqualTo(mac);
      }
      ct.andItem1EqualTo("1");
      List<AppSocket> socketList = appSocketDAO.selectByExample(example);
      List<AppSocketVo> voList = new ArrayList<AppSocketVo>();
      if(null != socketList && socketList.size()>0){
        Map<Integer, AppHouse> houseMap = new HashMap<Integer,AppHouse>();
        for(AppSocket socket: socketList){
          AppHouse house = queryLockHouseInfoFromCache(socket.getHouseId(), houseMap);
          AppSocketVo vo = new AppSocketVo();
          if(null != house){
            vo.setHouseAddress(house.getHouseAddress());
            vo.setHouseName(house.getHouseName());
          }else{
            vo.setHouseName("该房源已下线");
            vo.setHouseAddress("该房源已下线");
          }
          vo.setMac(socket.getMac());
          vo.setSocketName(socket.getName());
          if(null != mac){//这个用作查询详细的mac地址的设备的时候          
            vo.setWifiSsid(socket.getWifiSsid());
            vo.setWifiPassword(socket.getWifiPassword());
          }
          voList.add(vo);
        }
      }
      result = AppResult.newSusscessResult(voList);
    }
    return result;
  }
  
  /**
   * @description 查询用户信息
   * @param mobile
   */
  public AppResult queryMyInfo(String mobile) throws SQLException{
    AppResult result;
    AppSysUser user = queryUserInfo(mobile);
    if(null == user){
      result = AppResult.newFailResult("当前用户不存在");
    }else{
      MineVo mine = new MineVo();
      mine.setNickName(user.getNickName());
      mine.setPhoto(user.getPhoto());
      //查询用户下面的房源数量
      AppHouseExample houseEX = new AppHouseExample();
      houseEX.createCriteria().andLandlordIdEqualTo(user.getId())
      .andItem1EqualTo("1");
      int houseCount = appHouseDAO.countByExample(houseEX);
      mine.setHouseCount(houseCount);
      //查询用户的插头数量
      AppSocketExample socketEx = new AppSocketExample();
      socketEx.createCriteria().andManageUserIdEqualTo(user.getId())
      .andItem1EqualTo("1");
      int socketCount = appSocketDAO.countByExample(socketEx);
      mine.setSocketCount(socketCount);
      //查询管理员数量
      AppLandlordAuthExample authExample = new AppLandlordAuthExample();
      authExample.createCriteria().andLandlordIdEqualTo(user.getId()).andItem1EqualTo("1");
      int managerCount = appLandlordAuthDAO.countByExample(authExample);
      mine.setManagerCount(managerCount);
      
      //查询用户是否是房东
      AppSysUserRoleExample roleEx = new AppSysUserRoleExample();
      roleEx.createCriteria().andUserIdEqualTo(user.getId())
      .andRoleIdEqualTo(SystemConstants.SYS_ROLE_LANDLORD);
      mine.setLandlordFlag(appSysUserRoleDAO.countByExample(roleEx)>0?1:0);
      result = AppResult.newSusscessResult(swapObjectIntoList(mine));
    }
    return result;
  }
  
  private AppSysUser queryUserInfo(String mobile) throws SQLException{
    //查询用户信息
    AppSysUserExample userEx = new AppSysUserExample();
    userEx.createCriteria().andMobileEqualTo(mobile)
    .andStateEqualTo(1);
    List<AppSysUser> userList = appSysUserDAO.selectByExample(userEx);
    return (null == userList || userList.size() == 0)?null:userList.get(0);
  }
  
  private AppHouse queryLockHouseInfoFromCache(Integer houseId, Map<Integer,AppHouse> houseMap) throws SQLException{
    if(houseMap.containsKey(houseId)){
      return houseMap.get(houseId);
    }else{
      houseMap.put(houseId, queryAppHouseInfo(houseId));
      return houseMap.get(houseId);
    }
  }
  
  private AppHouse queryAppHouseInfo(Integer houseId) throws SQLException{
    return appHouseDAO.selectByPrimaryKey(houseId);
  }
  
  public <T> List<T> swapObjectIntoList(T t){
    List<T> rList = new ArrayList<T>();
    rList.add(t);
    return rList;
  }
}
